<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色分类权限管理</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: Arial, sans-serif;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 0 10px;
        }
        
        .btn-primary {
            background-color: #409eff;
            color: white;
        }
        
        .btn-default {
            background-color: #ecf5ff;
            color: #409eff;
        }
        
        .btn-danger {
            background-color: #f56c6c;
            color: white;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409eff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .category-tree {
            margin-top: 20px;
        }
        
        .category-item {
            padding: 10px;
            border: 1px solid #dcdfe6;
            margin-bottom: 5px;
            border-radius: 4px;
            display: flex;
            align-items: center;
        }
        
        .category-item .category-name {
            flex: 1;
            font-weight: bold;
        }
        
        .permission-item {
            display: flex;
            align-items: center;
            margin: 10px 0;
        }
        
        .permission-item label {
            margin-left: 10px;
            flex: 1;
        }
        
        .actions {
            margin-top: 20px;
            text-align: center;
        }
        
        .submenu {
            margin-left: 30px;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>角色分类权限管理 <span id="roleName"></span></h2>
            <button class="btn btn-default" onclick="history.back()">返回</button>
        </div>
        
        <div class="card">
            <h3>分类权限设置</h3>
            <div id="loadingIndicator" class="loading" style="display: none;">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
            <div class="category-tree" id="categoryTree">
                <!-- 分类树将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <div class="actions">
            <button class="btn btn-primary" onclick="savePermissions()">保存权限</button>
            <button class="btn btn-danger" onclick="clearPermissions()">清空权限</button>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    
    <script>
        // 当前角色ID
        const roleId = new URLSearchParams(window.location.search).get('id');
        // 当前角色拥有的分类权限
        let roleCategoryPermissions = [];
        // 所有分类数据
        let categoryData = [];
        // 选中的权限
        let selectedPermissions = new Set();
        
        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', async function() {
            if (!roleId) {
                alert('缺少角色ID参数');
                history.back();
                return;
            }
            
            showLoading(true);
            await Promise.all([
                loadRoleInfo(),
                loadCategories(),
                loadRoleCategoryPermissions()
            ]);
            showLoading(false);
            
            renderCategoryTree();
        });
        
        // 显示/隐藏加载指示器
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const categoryTree = document.getElementById('categoryTree');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                categoryTree.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                categoryTree.style.display = 'block';
            }
        }
        
        // 获取角色信息
        async function loadRoleInfo() {
            try {
                const response = await fetch(`/role/${roleId}`, {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const role = await response.json();
                    document.getElementById('roleName').textContent = `- ${role.name}`;
                } else {
                    console.error('获取角色信息失败:', response.status);
                }
            } catch (error) {
                console.error('获取角色信息异常:', error);
            }
        }
        
        // 获取分类数据
        async function loadCategories() {
            try {
                const response = await fetch('/api/category/tree', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    categoryData = result.data || [];
                } else {
                    console.error('获取分类数据失败:', response.status);
                    categoryData = []; // 确保categoryData是一个数组
                }
            } catch (error) {
                console.error('获取分类数据异常:', error);
                categoryData = []; // 确保categoryData是一个数组
            }
        }
        
        // 获取角色分类权限
        async function loadRoleCategoryPermissions() {
            try {
                const response = await fetch(`/role/${roleId}/category-policies`, {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const policies = result.data || [];
                    roleCategoryPermissions = policies;
                    // 将角色权限添加到选中集合中
                    policies.forEach(policy => {
                        // 策略格式: p, roleName, resource, action
                        if (policy.length >= 3) {
                            const resource = policy[1]; // /category/:id
                            const action = policy[2];   // post/edit/review
                            // 提取分类ID
                            const categoryId = resource.split('/')[2];
                            selectedPermissions.add(`${categoryId}:${action}`);
                        }
                    });
                } else {
                    console.error('获取角色分类权限失败:', response.status);
                    roleCategoryPermissions = [];
                }
            } catch (error) {
                console.error('获取角色分类权限异常:', error);
                roleCategoryPermissions = [];
            }
        }
        
        // 渲染分类树
        function renderCategoryTree() {
            const container = document.getElementById('categoryTree');
            container.innerHTML = '';
            
            function createCategoryItem(category) {
                const categoryItem = document.createElement('div');
                categoryItem.className = 'category-item';
                
                const hasChildren = category.children && category.children.length > 0;
                
                // 分类基本信息
                categoryItem.innerHTML = `
                    <div>
                        <span class="category-name">${category.name}</span>
                    </div>
                `;
                
                // 权限选择
                const permissionContainer = document.createElement('div');
                permissionContainer.style.marginLeft = '20px';
                permissionContainer.style.marginTop = '10px';
                
                // 为分类添加权限选项
                const permissions = ['post', 'edit', 'review'];
                const permissionLabels = ['投稿', '编辑', '审核'];
                
                permissions.forEach((perm, index) => {
                    const permissionItem = document.createElement('div');
                    permissionItem.className = 'permission-item';
                    permissionItem.innerHTML = `
                        <input type="checkbox" id="perm_${category.id}_${perm}" 
                               data-category="${category.id}" data-action="${perm}"
                               ${selectedPermissions.has(`${category.id}:${perm}`) ? 'checked' : ''}>
                        <label for="perm_${category.id}_${perm}">${permissionLabels[index]}权限</label>
                    `;
                    permissionContainer.appendChild(permissionItem);
                });
                
                categoryItem.appendChild(permissionContainer);
                
                // 子分类
                if (hasChildren) {
                    const submenuContainer = document.createElement('div');
                    submenuContainer.className = 'submenu';
                    
                    category.children.forEach(child => {
                        const childElement = createCategoryItem(child);
                        submenuContainer.appendChild(childElement);
                    });
                    
                    categoryItem.appendChild(submenuContainer);
                }
                
                return categoryItem;
            }
            
            categoryData.forEach(category => {
                const categoryItem = createCategoryItem(category);
                container.appendChild(categoryItem);
            });
            
            // 绑定复选框事件
            document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const categoryId = this.dataset.category;
                    const action = this.dataset.action;
                    const key = `${categoryId}:${action}`;
                    
                    if (this.checked) {
                        selectedPermissions.add(key);
                    } else {
                        selectedPermissions.delete(key);
                    }
                });
            });
        }
        
        // 保存权限
        async function savePermissions() {
            try {
                showLoading(true);
                
                // 先清空角色的所有分类权限
                await fetch(`/role/${roleId}/category-policies/clear`, {
                    method: 'POST',
                    credentials: 'include'
                });
                
                // 添加新选择的权限
                const permissionsToAdd = Array.from(selectedPermissions);
                let successCount = 0;
                
                for (const perm of permissionsToAdd) {
                    const [categoryId, action] = perm.split(':');
                    if (categoryId && action) {
                        try {
                            const response = await fetch(`/role/${roleId}/category-policies`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ 
                                    categoryId: parseInt(categoryId), 
                                    action 
                                }),
                                credentials: 'include'
                            });
                            
                            if (response.ok) {
                                successCount++;
                            }
                        } catch (error) {
                            console.error(`添加权限失败 (${categoryId}:${action}):`, error);
                        }
                    }
                }
                
                showLoading(false);
                alert(`权限保存完成，成功设置 ${successCount} 个权限`);
                // 重新加载权限
                await loadRoleCategoryPermissions();
            } catch (error) {
                showLoading(false);
                console.error('保存权限异常:', error);
                alert('保存权限时发生错误');
            }
        }
        
        // 清空权限
        async function clearPermissions() {
            if (!confirm('确定要清空该角色的所有分类权限吗？')) {
                return;
            }
            
            try {
                showLoading(true);
                const response = await fetch(`/role/${roleId}/category-policies/clear`, {
                    method: 'POST',
                    credentials: 'include'
                });
                
                if (response.ok) {
                    // 清空所有选中的复选框
                    document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                        checkbox.checked = false;
                    });
                    selectedPermissions.clear();
                    showLoading(false);
                    alert('权限已清空');
                } else {
                    showLoading(false);
                    alert('清空权限失败');
                }
            } catch (error) {
                showLoading(false);
                console.error('清空权限异常:', error);
                alert('清空权限时发生错误');
            }
        }
    </script>
</body>
</html>